package info.rflow.actionproviders;

import info.rflow.actions.*;
import info.rflow.graph.RWorkflowScene;
import info.rflow.graph.model.RBlockNode;
import info.rflow.model.RBlock;
import info.rflow.model.WorkflowOutputCache;
import org.netbeans.api.visual.action.PopupMenuProvider;
import org.netbeans.api.visual.widget.Widget;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;


/**
 * A context menu for the single configurable graph nodes. It contains common node action like removing,  etc. .
 *
 * @author Holger Brandl
 */
public class NodePopUpProvider implements PopupMenuProvider {

    private RWorkflowScene rWorkflowScene;


    public NodePopUpProvider(RWorkflowScene rWorkflowScene) {
        this.rWorkflowScene = rWorkflowScene;
    }


    public JPopupMenu getPopupMenu(final Widget widget, Point point) {
        JPopupMenu menu = new JPopupMenu("node menu");

//        JMenuItem item = new JMenuItem("expand defaults");
        menu.add(new JMenuItem(new ExecuteBlockAction(rWorkflowScene)));


        // add a jump to line action
        Set<?> selectedObjects = rWorkflowScene.getSelectedObjects();
        Collection<RBlock> selectedBlocks = new ArrayList<RBlock>();
        for (Object selectedObject : selectedObjects) {
            if (selectedObject instanceof RBlockNode) {
                RBlockNode selBlock = (RBlockNode) selectedObject;
                selectedBlocks.add(selBlock.getRBlock());

                // add items for each block individually todo why in the loop
                menu.add(new JMenuItem(new OpenCurrentBlockInEditor(selBlock.getRBlock())));
            }
        }

        menu.add(new JMenuItem(new ResetBlockAction(selectedBlocks)));
        menu.add(new JSeparator());

        // add open buttons for all outputs
        if (selectedBlocks.size() == 1) {
            RBlock rBlock = selectedBlocks.iterator().next();

            WorkflowOutputCache outputCache = rBlock.getWorkflowModel().getOutputCache();
            for (File file : outputCache.getOutputs(rBlock.getName())) {
                if (file.getName().endsWith(".RData")) {
                    menu.add(new JMenuItem(new ShowInExcelAction(file.getName(), rBlock)));
                } else {
                    menu.add(new JMenuItem(new OpenFileAction(file)));
                }
            }

        }

        return menu;
    }
}